#pragma once
#include <osg/Image>
#include <osg/Texture2D>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include "core/CMacro.h"

class OImage : public osg::Image {
public:
	OImage(int w, int h, bool hasAlphaChannel = true) {
		this->allocateImage(w, h, 1, hasAlphaChannel ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE);
	}

	OImage(CByteArray& bytes, int w, int h, bool hasAlphaChannel = true) : OImage(w, h, hasAlphaChannel) {
		this->setData(bytes.data(), AllocationMode::USE_NEW_DELETE);
	}

	OImage(const std::string& imgPath) {
		osg::ref_ptr<osg::Image> image = osgDB::readImageFile(imgPath);
		if (!image || !image->valid())
			EXIT("image is invalid!");
		this->allocateImage(image->s(), image->t(), image->r(), image->getPixelFormat(), image->getDataType());
		this->setData(image->data(), AllocationMode::USE_NEW_DELETE);
	}

	~OImage() { std::cout << ">>> ~OImage" << std::endl; }

	osg::Texture2D* toTexture2D() {
		auto texture = new osg::Texture2D(this);
		texture->setResizeNonPowerOfTwoHint(false);
		return texture;
	}

	bool saveToLocal(const std::string& path) {
		return osgDB::writeImageFile(*this, path);
	}
};